package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 令牌校验过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1. 获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();//得到请求路径
        log.info("请求了路径：{}", url);
        //2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行.   登录请求/login
        if(url.contains("login")){
            log.info("登录操作,直接放行");
            filterChain.doFilter(request, response);
            return;//放行，后面的代码就不再执行
        }
        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");
        //4. 判断令牌是否存在，
        if(!StringUtils.hasLength(token)){
            log.info("请求头中无token");
            //如果不存在，响应 401
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //5. 解析token，
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer loginUserId = claims.get("id", Integer.class);
            System.out.println("loginUserId = " + loginUserId);
            //存入ThreadLocal
            CurrentHolder.setCurrentId(loginUserId);
            log.info("解析到token中的信息：{}", claims);
        } catch (Exception e) {
            log.error("解析token失败", e);
            //如果解析失败，响应 401
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //6. 放行
        log.info("令牌校验通过，放行");
        filterChain.doFilter(request, response);
        //controller执行后回来的代码
        // 清除线程本地变量，避免内存泄漏
        CurrentHolder.remove();
    }
}
